package io.yuncheng.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.yuncheng.common.annotation.DataFilter;
import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.exception.RRException;
import io.yuncheng.common.utils.Constant;
import io.yuncheng.common.utils.PageUtils;
import io.yuncheng.common.utils.Query;
import io.yuncheng.common.utils.SysDictConstant;
import io.yuncheng.modules.sys.dao.SysDeptDao;
import io.yuncheng.modules.sys.entity.SubApplicationEntity;
import io.yuncheng.modules.sys.entity.SysDeptEntity;
import io.yuncheng.modules.sys.service.SysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {

    @Resource
    SysDeptDao deptDao;
    @Resource
    private DictConfig dictConfig;

    @Override
    @DataFilter(subDept = true, user = false, tableAlias = "t1")
    public List<SysDeptEntity> queryList(Map<String, Object> params) {
        return baseMapper.queryList(params);
    }

    @Override
    public List<Long> queryDetpIdList(Long parentId) {
        return baseMapper.queryDetpIdList(parentId);
    }

    @Override
    public List<SysDeptEntity> queryDeptList(Long parentId) {
        return baseMapper.queryDeptList(parentId);
    }

    @Override
    public List<SysDeptEntity> queryLevelTwoListByDept(Long deptId) {
        List<SysDeptEntity> levelOneList = queryDeptList(deptId);
        List<Object> collect = levelOneList.stream().map(SysDeptEntity::getDeptId).collect(Collectors.toList());
        QueryWrapper<SysDeptEntity> queryWrapper = new QueryWrapper<>();
        if(ObjectUtils.isEmpty(collect)){
            return new ArrayList<>();
        }
        queryWrapper.in("parent_id", collect);
        List<SysDeptEntity> list = list(queryWrapper);
//        List<SysDeptEntity> levelTwoList = new ArrayList<>();
//        levelOneList.forEach(a -> levelTwoList.addAll(queryDeptList(a.getDeptId())));
        return list;
    }

    @Override
    public List<SysDeptEntity> queryListByType(Integer type) {
        QueryWrapper<SysDeptEntity> queryWrapper = new QueryWrapper<>();
        SysDeptEntity sysDeptEntity = new SysDeptEntity();
        sysDeptEntity.setType(type);
        queryWrapper.setEntity(sysDeptEntity);
        return list(queryWrapper);
    }


    @Override
    public SysDeptEntity queryByName(String name) {
        SysDeptEntity sysDeptEntity = baseMapper.selectOne(new QueryWrapper<SysDeptEntity>().eq("name", name));
        return sysDeptEntity;
    }

    @Override
    public SysDeptEntity queryByUnique(String unique) {
        SysDeptEntity sysDeptEntity = baseMapper.selectOne(new QueryWrapper<SysDeptEntity>().eq("unique_id", unique));
        return sysDeptEntity;
    }

    @Override
    public List<Long> getSubDeptIdList(Long deptId) {
        //部门及子部门ID列表
        List<Long> deptIdList = new ArrayList<>();

        //获取子部门ID
        List<Long> subIdList = queryDetpIdList(deptId);
        getDeptTreeList(subIdList, deptIdList);

        return deptIdList;
    }

    /**
     * 递归
     */
    private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList) {
        for (Long deptId : subIdList) {
            List<Long> list = queryDetpIdList(deptId);
            if (list.size() > 0) {
                getDeptTreeList(list, deptIdList);
            }

            deptIdList.add(deptId);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Object parentId = params.get("parentId");
        Object status = params.get("status");
        Object notType = params.get("notType");
        Object type = params.get("type");
        IPage<SysDeptEntity> page = this.page(
                new Query<SysDeptEntity>().getPage(params),
                new QueryWrapper<SysDeptEntity>()
                        .eq(parentId != null, "parent_id", parentId)
                        .eq(status != null, "status", status)
                        .eq(type != null, "type", type)
                        .ne(notType != null, "type", notType)
        );
        List<SysDeptEntity> records = page.getRecords();
        records.forEach(a -> {
            SysDeptEntity byId = getById(a.getParentId());
            if(!ObjectUtils.isEmpty(byId)){
                a.setParentName(byId.getName());
            }
        });
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageConfirm(Map<String, Object> params) {
        params.put("status", 1);
        params.put("notType", Constant.DeptTypeEnum.APP.getValue());
        return queryPage(params);
    }
    @Override
    public void checkEntity(SysDeptEntity deptEntity,String msg){
        //二级部门
        if(deptEntity.getType().equals(Constant.DeptTypeEnum.DEPT_2.getValue())){
            checkDept(deptEntity.getParentId(),msg);
        }
        //应用级别的
        if(deptEntity.getType().equals(Constant.DeptTypeEnum.APP.getValue())){
            checkByParentDeptId(deptEntity.getParentId(),msg);
        }
    }

    @Override
    public void checkByParentDeptId(Long deptId, String msg) {
        SysDeptEntity byId = getById(deptId);
        checkDept(byId.getParentId(),msg);
    }
    @Override
    public void checkDept(Long levelOne,String msg){
        //省级
        String deptIdStr = dictConfig.getSysDictValue(SysDictConstant.SYS_LEVEL, Constant.DICT_DEFAULT_CODE);
        //一级部门
        List<Long> parentLevelOne = queryDetpIdList(Long.valueOf(deptIdStr));
        if(!parentLevelOne.contains(levelOne)){
            String sysDictValue = dictConfig.getSysDictValue(SysDictConstant.SYS_LEVEL_TYPE_REMARK, deptIdStr);
            throw new RRException("请选择"+ sysDictValue + "下的" + msg);
        }
    }

    @Override
    public SysDeptEntity saveByApp(SubApplicationEntity subApplication) {

        SysDeptEntity sysDeptEntity = new SysDeptEntity();
        sysDeptEntity.setName(subApplication.getUniqueAppId());
        sysDeptEntity.setStatus(Constant.StatusType.NORMAL.getValue());
        sysDeptEntity.setType(Constant.DeptTypeEnum.APP.getValue());
        sysDeptEntity.setParentId(subApplication.getParentDeptId());
        //保存到部门
        sysDeptEntity.setName(subApplication.getAppName());
        deptDao.insertReturnId(sysDeptEntity);
        return sysDeptEntity;
    }


}
